package com.itbbs.oss.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.itbbs.oss.service.api.OssService;
import com.itbbs.oss.utils.ConstantPropertiesUtils;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

/**
 * @program: bbs-system
 * @ClassName OssServiceImpl
 * @description:
 * @author: 7
 * @create: 2021-06-04 12:10
 * @Version 1.0
 **/
@Service
public class OssServiceImpl implements OssService {
    @Override
    public String uploadFileAvatar(MultipartFile file) {

        // 获取必要数据
        String endpoint = ConstantPropertiesUtils.END_POINT;
        String accessKeyId = ConstantPropertiesUtils.ACCESS_KEY_ID;
        String accessKeySecret = ConstantPropertiesUtils.ACCESS_KEY_SECRET;
        String bucketName = ConstantPropertiesUtils.BUCKET_NAME;

        InputStream inputStream = null;
        try {
            // 创建Oss实例
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

            // 获取上传文件的数据流
            inputStream = file.getInputStream();

            // 获取文件的名称
            String fileName = file.getOriginalFilename();

            // 在文件名称里加上随机唯一的值
            String uuid = UUID.randomUUID().toString();

            fileName = uuid+fileName;

            // 获取当前日期文件按日期分类，时间需要格式化
            String datePath = new DateTime().toString("yyyy/MM/dd");

            // 拼接日期
            // yyyy/MM/dd/uuid+fileName.jpg
            fileName = datePath + "/" +fileName;


            // 调用oss实例方法上传
            ossClient.putObject(bucketName, fileName, inputStream);

            // 关闭实例
            ossClient.shutdown();

            // 返回url用于存放数据库
            String url = "http://"+bucketName+"."+endpoint+"/"+fileName;
            return url;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }

    }
}
